#include "surface_point.hh"
#include "mesh_geometry.hh"
#include "ply_reader.hh"

using namespace std;
using namespace cgmath;

mesh_geometry::mesh_geometry (const char* ply_file)
{
  read_ply(ply_file, triangles);
}

double mesh_geometry::hit (const cgmath::ray_3d& r) const
{
  // Go through all triangles in the mesh.
  double t = std::numeric_limits<double>::max();

  // barycentric coordinates
  double a;
  double b;
  double c;

  unsigned nearest = triangles.size();
  for (unsigned i = 0; i < triangles.size(); ++i)
    {
      double tmp;
      if (cgmath::intersect(r, triangles[i], tmp, a, b, c) && tmp < t)
        {
          t = tmp;
          nearest = i;
        }
    }
  
  if (nearest < triangles.size())
    {
      hit_point = r(t);
      hit_normal = cgmath::normal<double> (triangles[nearest]);
      return t;
    }
  else
    return std::numeric_limits<double>::infinity();
}

void mesh_geometry::hit_surface_point (surface_point& pt) const
{
  pt.point = hit_point;
  pt.normal = hit_normal;
  pt.u = 0.0;
  pt.v = 0.0;
}
